﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Reflection;
using System.Web.SessionState;

namespace TA.Turbo
{
	/// <summary>
	/// HTTP module which provides upload progress support.
	/// </summary>
	public class FileUploadHttpModule : IHttpModule
	{
		#region PUBLIC
		#region INIT
		/// <summary>
		/// Ctor.
		/// </summary>
		public FileUploadHttpModule()
		{
			//
			// TODO: Add constructor logic here
			//
		}
		#endregion
		#region METHODS
		/// <summary>
		/// Dispose.
		/// </summary>
		public void Dispose()
		{
		}
		/// <summary>
		/// Init.
		/// </summary>
		/// <param name="context"></param>
		public void Init(HttpApplication context)
		{
			context.BeginRequest += new EventHandler(context_BeginRequest);
		}
		#endregion
		#endregion
		#region INTERNAL
		#region METHODS
		void context_BeginRequest(object sender, EventArgs e)
		{
			HttpApplication app = (HttpApplication)sender;
			HttpContext context = app.Context;
			HttpRequest request = context.Request;

			if (this.IsFileUploadRequest(request))
			{
				HttpWorkerRequest wr = this.GetWorkerRequest(context);
				if (wr != null)
				{
					FileUploadOperation oper = new FileUploadOperation(context, wr);
					oper.Process();
				}

				//HttpWorkerRequest wr = this.GetWorkerRequest(context);
				//if (wr != null)// && token != null
				//{
				//  string token = context.Request.QueryString["t"];
				//  FileUploadOperation oper = new FileUploadOperation(context, wr, token);
				//  FileUploadOperation.Register(context, oper);
				//  oper.Process();
				//}
			}
		}
		bool IsFileUploadRequest(HttpRequest request)
		{
			return (request.RequestType.Equals("POST") && request.ContentType.Contains("multipart/form-data"));
		}
		private HttpWorkerRequest GetWorkerRequest(HttpContext context)
		{
			try
			{
				return (HttpWorkerRequest)((IServiceProvider)HttpContext.Current).GetService(typeof(HttpWorkerRequest));
			}
			catch
			{
				PropertyInfo property = context.GetType().GetProperty("WorkerRequest", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
				if (property != null)
				{
					return (HttpWorkerRequest)property.GetValue(context, null);
				}
				return null;
			}
		}
		#endregion
		#endregion
	}
}